import base64
import pickle

from django.conf import settings
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from xiaoyu_mall.apps.users.models import TbSku


# Create your views here.
class CartsView(View):
    def get(self, request):
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 创建连接到redis的对象
            redis_conn = get_redis_connection('carts')
            # 查询user_id、count与sku_id构成的购物车记录
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            # 查询勾选的商品smembers 命令返回集合中的所有的成员
            redis_selected = redis_conn.smembers('selected_%s' % user.id)
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    "count": int(count),
                    "selected": sku_id in redis_selected
                }
        else:
            # 用户未登录，查询cookies购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 对 cart_str进行编码，获取字节类型的数据
                cart_str_bytes = cart_str.encode()
                # 对cart_str_bytes进行解码，获取明文数据
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 对cart_dict_bytes反序列化，转换成Python能识别的字典类型的数据
                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}
        # 构造响应数据
        sku_ids = cart_dict.keys()
        # 一次性查询出所有的skus
        skus = TbSku.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'count': cart_dict.get(sku.id).get('count'),
                # 将True，转'True'，方便json解析
                'selected': str(cart_dict.get(sku.id).get('selected')),
                'name': sku.name,
                'default_image_url': settings.STATIC_URL +
                                     'images/goods/' + sku.default_image.url + '.jpg',
                'price': str(sku.price),
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
                'stock': sku.stock
            })
        context = {
            'cart_skus': cart_skus
        }
        # 渲染购物车页面
        return render(request, 'cart.html', context)
